package com.lb.zookeeper.demo;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 * @Title: WatcherDemo
 * @Description: TODO
 * @Author lb
 * @Date 2019/04/04  17:19
 */
public class WatcherDemo {
    public static void main(String[] args) throws Exception {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zooKeeper = new ZooKeeper("192.168.245.130:2181,192.168.245.131:2181," +
                "192.168.245.132:2181", 4000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println("默认事件："+watchedEvent.getType()+"->"+watchedEvent.getPath());
                if (Event.KeeperState.SyncConnected == watchedEvent.getState()){
                    countDownLatch.countDown();
                }
            }
        });
        countDownLatch.await();



        zooKeeper.create("/zk-persis-lb", "1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        //exists getData getChildren

        //通过exist绑定事件
        Stat exists = zooKeeper.exists("/zk-persis-lb", new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println(watchedEvent.getType() + "->" + watchedEvent.getPath());
                try {
                    zooKeeper.exists(watchedEvent.getPath(), true);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        exists = zooKeeper.setData("/zk-persis-lb", "我是更改之后的数据".getBytes(), exists.getVersion());
        Thread.sleep(1000);
        zooKeeper.create("/zk-persis-lb/libin", "2".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        zooKeeper.delete("/zk-persis-lb", exists.getVersion());
    }
}
